package com.car.order.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.car.commons.web.util.StateUtil;
import com.car.order.entity.ServiceOrderInfo;
import com.car.order.exception.serveOrderInfo.ServeOrderInfoException;
import com.car.order.mapper.ServiceOrderInfoMapper;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.UUID;

@Component
public class ServeOrderRefundUtil {
    @Autowired
    private AlipayUtil alipayUtil;
    @Autowired
    private ServiceOrderInfoMapper orderInfoMapper;
    @Autowired
    private AlipayClient alipayClient;

    @RabbitHandler
    public void refund(String orderNum) throws Exception {
//设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = orderNum;
        ServiceOrderInfo ServeOrderInfo = orderInfoMapper.selectById(out_trade_no);
//支付宝交易号
//        String trade_no = new String(alipayRequest.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
//请二选一设置
//需要退款的金额，该金额不能大于订单金额，必填
        BigDecimal refund_amount = ServeOrderInfo.getMoney();
//退款的原因说明
        String refund_reason = "退款";
//标识一次退款请求，同一笔交易分多次退款的话，out_request_no每次传值都不能重复，必须保证唯一性
//        String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ UUID.randomUUID().toString().replace("-","") +"\"}");

//请求
        String result = alipayClient.execute(alipayRequest).getBody();
        String code = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("code").toString();
        String fundChange = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_refund_response").toString()).get("fund_change").toString();
        if (!(code.equals("10000") && fundChange.equals("Y"))) {
            throw new Exception("退款错误");
        }

        ServeOrderInfo.setOrderState(StateUtil.SERVE_ORDER_STATE_REFUND);
        Integer integer = orderInfoMapper.updateById(ServeOrderInfo);
        if (integer == 0) {
            throw new ServeOrderInfoException(500, "退款失败");
        }

    }
}
